/**
 * 分页查询工具类
 * Created by zhangsong on 2017/9/8.
 */

// 模型,查詢條件,查詢顯示的列,
/**
 * 分页,每页最多100条记录
 * @param schema
 * @param options 参数对象
 *  page        第几页,默认第一页
 *  pageSize    每页显示条数
 *  query       查询条件
 *  column      查询显示的列
 *  sort        排序集合
 *  populate
 * @param callback    回调函数,不传默认返回 promise 对象
 * @returns {Promise}
 */
function findByPage(schema, {page, pageSize, query = {}, column, sort, populate} = {query: {}}, callback) {
  if(!page){
    page = 1;
  }
  if(!pageSize){
    pageSize = 20;
  }else if(pageSize>100){
    pageSize = 100;
  }
  function count() {
    return schema.count(query);
  }
  function find() {
    let find = null;
    if(column){
      find = schema.find(query, column);
    }else{
      find = schema.find(query);
    }
    find = find.skip((page-1)*pageSize).limit(pageSize);
    if(sort){
      find = find.sort(sort);
    }
    if(populate){
      find = find.populate(populate);
    }
    return find;
  }
  let promiseArray = [];
  promiseArray.push(count());
  promiseArray.push(find());
  let promise = new Promise((resolve, reject)=> {
    Promise.all(promiseArray).then((result)=> {
      let json = {};
      json.count = result[0];
      json.page = page;
      json.pageSize = pageSize;
      json.data = result[1];
      resolve(json);
    }).catch((err)=> {
      reject(err);
    });
  });
  if(callback){
    promise.then((result)=> {
      callback(null, result);
    }).catch((err)=> {
      callback(err, null);
    });
  }else{
    return promise;
  }
}

module.exports = findByPage;